<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>车辆管理</el-breadcrumb-item>
      <el-breadcrumb-item>车辆维护</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>
          <el-row :gutter="100">
            <el-col :span="10"
              ><div class="grid-content bg-purple">
                <el-input
                  placeholder="根据车牌号查找"
                  v-model="queryInfo.name"
                  @blur="kong()"
                >
                  <el-button slot="append" icon="el-icon-search" @click="find()"
                    >搜索</el-button
                  >
                  <i slot="prefix" class="el-input__icon el-icon-loading"></i>
                </el-input></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <el-button type="primary" @click="dialogFormVisible = true"
                  >车辆登记</el-button
                >
              </div></el-col
            >
            <el-dialog
              :close-on-click-modal="false"
              @close="resetForm('ruleForm')"
              title="车辆登记"
              :visible.sync="dialogFormVisible"
            >
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="车牌号" prop="carnum">
                  <el-input
                    type="text"
                    v-model="ruleForm.carnum"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="车身颜色" prop="carcoloer">
                  <el-input
                    type="text"
                    v-model="ruleForm.carcoloer"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="车型" prop="pass">
                  <el-radio border v-model="ruleForm.radio" label="自动挡"
                    >自动挡</el-radio
                  >
                  <el-radio border v-model="ruleForm.radio" label="手动挡"
                    >手动挡</el-radio
                  >
                </el-form-item>
                <el-form-item label="车辆注册日期" prop="pass">
                  <div class="block">
                    <span class="demonstration"></span>
                    <el-date-picker
                      v-model="ruleForm.value1"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </div>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="addcar">提交</el-button>
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
              </el-form>
              <!-- <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false"
                  >确 定</el-button
                >
              </div> -->
            </el-dialog>
          </el-row>
        </span>
      </div>
      <div class="text item">
        <el-table :data="userlist" :border="true" style="width: 100%">
          <el-table-column type="index" width="50" :index="indexMethod">
          </el-table-column>
          <el-table-column label="车辆注册日期" width="anto">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{
                scope.row.carManufactureDate
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="车牌号" width="anto">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.carNumber }}</el-tag>
              </div>
            </template> </el-table-column
          ><el-table-column label="车身颜色" width="anto">
            <template slot-scope="scope">
              <div slot="reference" class="name-emergencyContact">
                <el-tag size="medium">{{ scope.row.carColoer }}</el-tag>
              </div>
            </template> </el-table-column
          ><el-table-column label="自动or手动" width="anto">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.carStructure }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="showedit(scope.row.carId)"
                >编辑</el-button
              >

              <el-button
                size="mini"
                type="danger"
                @click="removeUserById(scope.row.carId)"
                >删除</el-button
              >
              <el-dialog
                :close-on-click-modal="false"
                title="编辑信息"
                :visible.sync="dialogFormVisible1"
              >
                <el-form
                  :model="editForm"
                  status-icon
                  ref="ruleForm"
                  label-width="100px"
                >
                  <el-form-item label="车牌号" prop="carnum">
                    <el-input
                      type="text"
                      v-model="editForm.carNumber"
                      autocomplete="off"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="车身颜色" prop="carcoloer">
                    <el-input
                      type="text"
                      v-model="editForm.carColoer"
                      autocomplete="off"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="车型" prop="pass">
                    <el-radio
                      border
                      v-model="editForm.carStructure"
                      label="自动挡"
                      >自动挡</el-radio
                    >
                    <el-radio
                      border
                      v-model="editForm.carStructure"
                      label="手动挡"
                      >手动挡</el-radio
                    >
                  </el-form-item>
                  <el-form-item label="车辆注册日期" prop="pass">
                    <div class="block">
                      <span class="demonstration"></span>
                      <el-date-picker
                        v-model="editForm.carManufactureDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                      >
                      </el-date-picker>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="addeditcar()"
                      >提交</el-button
                    >
                  </el-form-item>
                </el-form>
                <!-- <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false"
                  >确 定</el-button
                >
              </div> -->
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="length"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    //验证车牌号的合法性
    var checkcarnum = (rule, value, callback) => {
      callback;
      // const regcarnumber =
      //   /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
      // if (regcarnumber.test(value)) {
      //   return callback();
      // }
      // callback(new Error("请输入正确的车牌号"));
    };

    return {
      queryInfo: {
        name: "",
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条数据
        pageSize: 5,
      },
      userlist: [],
      length: 0,
      ruleForm: {
        carnum: "",
        carcoloer: "",
        radio: "自动挡",
        value1: "",
      },
      editForm: {},
      rules: {
        carnum: [
          { required: true, message: "请输入车牌号", trigger: "blur" },
          { validator: checkcarnum, trigger: "blur" },
        ],
        carcoloer: [
          { required: true, message: "请输入车身颜色", trigger: "blur" },
        ],
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      formLabelWidth: "120px",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async addeditcar() {
      const { data: res } = await this.$http.put("/car/update", {
        carId: this.editForm.carId,
        carNumber: this.editForm.carNumber,
        carStructure: this.editForm.carStructure,
        carColoer: this.editForm.carColoer,
        carManufactureDate: this.editForm.carManufactureDate,
      });
      if (res.code !== 200) {
        return this.$message.error("更改用户信息失败！");
      }
      this.$message.success("更改用户信息成功");
      // 更改信息成功后关闭对话框
      this.dialogFormVisible1 = false;
      //刷新页面
      this.getUserList();
    },
    async showedit(id) {
      this.dialogFormVisible1 = true;
      const { data: res } = await this.$http.get("/car/getCarById/" + id);
      this.editForm = res.restData;
    },
    kong() {
      if (this.queryInfo.name === "") {
        this.getUserList();
      }
    },
    async find() {
      if (this.queryInfo.name === "") {
        this.$message.error("查找用户失败,请输入信息！");
      }
      // const { data: res } = await this.$http.get("/car/getname/" + this.input1);
      this.getUserList();
      // this.userlist = res;
    },
    //分页数据序列号 index
    indexMethod(index) {
      if (this.queryInfo.pageNum === 1) {
        return index + 1;
      } else {
        return (
          this.queryInfo.pageSize * this.queryInfo.pageNum +
          index -
          this.queryInfo.pageSize +
          1
        );
      }
    },
    //分页逻辑
    // 监听页面容量改变的事件
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getUserList();
      // console.log(`每页 ${val} 条`);
    },
    // 监听 页码值 改变的事件

    handleCurrentChange(val) {
      this.queryInfo.pageNum = val;
      this.getUserList();

      // console.log(`当前页: ${val}`);
    },
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const { data: res } = await this.$http.delete("/car/deleteById/" + id);

      if (res.code !== 200) {
        return this.$message.error("删除用户失败！");
      }

      this.$message.success("删除用户成功！");
      this.getUserList();
    },
    // 获取更新用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("/car/query/", {
        params: this.queryInfo,
      });
      // console.log(res);
      this.userlist = res.restData.list;
      this.length = res.restData.total;
    },
    async addcar() {
      // 可以发起添加用户的网络请求
      if (this.ruleForm.carnum && this.ruleForm.carcoloer) {
        const { data: res } = await this.$http.post("/car/insert", {
          carNumber: this.ruleForm.carnum,
          carStructure: this.ruleForm.radio,
          carColoer: this.ruleForm.carcoloer,
          carManufactureDate: this.ruleForm.value1,
        });

        if (res !== 1) {
          this.$message.error("添加用户失败！");
        }

        this.$message.success("添加用户成功！");
        // 隐藏添加用户的对话框
        (this.dialogFormVisible = false),
          // 重新获取用户列表数据
          this.getUserList();
      } else {
        this.$message.error("添加用户失败,请输入完整的信息！");
      }
    },

    shchu() {
      this.$refs[formName].resetFields();
    },
    resetForm(formName) {
      if (!this.ruleForm.carcoloer) {
        this.$message.info("已取消登记");
      }
      this.$refs[formName].resetFields();
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
  },
};
</script>

<style>
.div {
  width: 100%;
  height: 100%;
}
.el-card__body {
  margin-top: -30px;
}
.el-pagination {
  margin-left: 15%;
}
</style>